import axios from 'axios'
import { useAuthStore } from '@/stores/authStore'
import { refreshTokenApi } from '@/api/auth'

const service = axios.create({
  baseURL: '/api', // 代理后端接口
  timeout: 10000
})

// 请求拦截器：自动加 token
service.interceptors.request.use(config => {
  const token = localStorage.getItem('token')
  // console.log('[Request] Token from localStorage:', token ? token.substring(0, 20) + '...' : 'null')

  // 检查token是否过期
  if (token) {
    try {
      const payload = JSON.parse(atob(token.split('.')[1]))
      const exp = payload.exp * 1000 // 转换为毫秒
      const now = Date.now()
      // console.log('[Request] Token过期时间:', new Date(exp).toLocaleString())
      // console.log('[Request] 当前时间:', new Date(now).toLocaleString())
      // console.log('[Request] Token是否过期:', now > exp)
    } catch (e) {
      // console.log('[Request] 无法解析token:', e.message)
    }

    config.headers['Authorization'] = `Bearer ${token}`
  } else {
    // console.log('[Request] No token found in localStorage')
  }
  return config
}, error => Promise.reject(error))

// 响应拦截器：处理 token 失效
service.interceptors.response.use(
  response => {
    // console.log('[Response] 成功响应:', response.status)
    return response.data;
  },
  async error => {
    console.log('[Response] 错误响应:', error.response?.status, error.response?.data)
    console.log('[Response] 错误详情:', error.message)

    if (error.response && error.response.status === 401) {
      // 防止无限重试
      if (error.config._retry) {
        console.log('[Response] 已经重试过，不再重试')
        const authStore = useAuthStore()
        authStore.logout()
        window.location.href = '/auth/loginpage'
        return Promise.reject(error)
      }

      // 获取refresh token
      const refreshToken = localStorage.getItem('refreshToken')

      // 如果有refresh token，尝试自动刷新
      if (refreshToken) {
        try {
          console.log('[Response] 尝试刷新token')
          error.config._retry = true // 标记已重试

          const res = await refreshTokenApi(refreshToken)
          console.log('[Response] 刷新token响应:', res)

          if (res.code === 200) {
            // 刷新成功，更新token
            const authStore = useAuthStore()
            authStore.setAuthData({
              token: res.data.AccessToken,
              refreshToken: res.data.RefreshToken,
              user: authStore.user
            })

            // 更新请求头中的token
            error.config.headers['Authorization'] = `Bearer ${res.data.AccessToken}`

            console.log('[Response] Token刷新成功，重试原请求')
            // 重试原请求
            return service.request(error.config)
          } else {
            console.log('[Response] Token刷新失败:', res.message)
          }
        } catch (refreshError) {
          console.error('Token刷新失败:', refreshError)
        }
      }

      // 刷新失败或无refresh token，清除认证信息并跳转登录
      const authStore = useAuthStore()
      authStore.logout()
      window.location.href = '/auth/loginpage'
    } else if (error.response && error.response.status === 403) {
      // 权限不足，返回统一的错误信息
      return Promise.reject({
        code: 403,
        message: '无该权限'
      })
    }

    return Promise.reject({
      code: error.response?.status || 500,
      message: error.response?.data?.message || error.message || '未知错误'
    })
  }
)

// 添加一个测试函数
export const testTokenRefresh = () => {
  console.log('[Test] 开始测试token刷新')
  // 手动设置一个过期的token来触发401
  localStorage.setItem('token', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI4NzVmNGU0MS1kNGIwLTRhYzAtOWM1My1iMjQ4NTExMDFkZGMiLCJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNzUzOTQyMDkxLCJpc3MiOiJVbml2ZXJzYWwuQXBpIiwiYXVkIjoiVW5pdmVyc2FsLkFwaVVzZXIifQ.expired')
  return service.get('/menu/GetCurrentUserMenus') // 这个接口需要认证
}

export default service
